import logging
from eshop.lib.base import *

log = logging.getLogger(__name__)

class LoginController(BaseController):

    def login(self):
        return render_response('/admin/user_edit.mako')
        
    def logout(self):
        return render_response('/admin/user_edit.mako')        
    
    def login_check(self):
        username = request.params.get('username', '').strip().lower()
        password = request.params.get('password', '').strip()        
        hash = sha.new()
        hash.update(password)        
        password_digest = hash.digest()        
        users = self.session.query(User).select_by(
            username=username, 
            password=password_digest)                
        
        if len(users) > 1:
            c.message="More than one user in database with username=%s found" % username
            return render_response('mako',"/account_signin.mak")
        elif not users:
            c.message="No such user %s" % username
            return render_response('mako',"/account_signin.mak")
            
        user = users[0]        
        request.environ['paste.auth_tkt.set_user'](username)
        user.lastlogin = datetime.now()
        self.session.save(user)
        self.session.flush()        
        redirect_to(controller='quote', action='index')        
    
        
   
